package com.example.actflow.model;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class LogicItem {
    public enum Type { CONDITION, ACTION }

    public LogicItem.Type type;
    public String target;
    public String param;
    public String varName;
    public  String compareOp;   // 条件时用的比较操作
    public String actionType;  // 动作时用的动作类型
    public Double delay = 0.0;
    public List<LogicItem> children = new ArrayList<>();

    public LogicItem() {}

    public LogicItem(LogicItem.Type type, String param, String varName) {
        this.type = type;
        this.param = param;
        this.varName = varName;
    }

    public static LogicItem createCondition(String target, String compareOp, String param, String varName) {
        LogicItem item = new LogicItem();
        item.type = Type.CONDITION;
        item.target = target;
        item.compareOp = compareOp;
        item.param = param;
        item.varName = varName;
        return item;
    }


    public static LogicItem createAction(String target, String actionType, Double delay ) {
        LogicItem item = new LogicItem();
        item.type = Type.ACTION;
        item.target = target;
        item.actionType = actionType;
        item.delay = delay;
        return item;
    }


    public boolean isFolder() {
        return type == LogicItem.Type.CONDITION;
    }

    @Override
    public String toString() {
        if (type == LogicItem.Type.ACTION) {
            return "[动作] " +target+" "+ (actionType != null ? actionType : param) +" 延迟(\""+formatDouble(delay)+"\")";
        }
        String opPart = (param != null && !param.isEmpty()) ? "（" + param + "）" : "";

        return "[条件] " +target+" "+ compareOp + opPart + (varName != null && !varName.isEmpty() ? " " + varName : "");
    }
    public static String formatDouble(double value) {
        DecimalFormat df = new DecimalFormat("0.##"); // 最多保留2位小数，末尾0自动去除
        return df.format(value);
    }
}
